const fs = require('fs');
const path =require('path')

//判断是否可以访问
exports.exists = async filePath => {
	return new Promise( resolve => {
		fs.exists(filePath, (e) => {
		  if(e){
		  	resolve([null])
		  }
		  resolve([`file not exist [${filePath}]`])
		});
	})
}

exports.write = async (logFile,data) => {
	return new Promise( resolve => {
		fs.writeFile(logFile, data, (err) => {
		  if (err) {
		    resolve(['写入失败'])
		  } else {
		    resolve([])
		  }
		});
	})
}


//追加文件
exports.appendWrite = async (logFile,data) => {
	return new Promise( resolve => {
		fs.writeFile(logFile, data, {flag: 'a'}, (err) => {
		  if (err) {
		    resolve(['写入失败'])
		  } else {
		    resolve([])
		  }
		});
	})
}

exports.getFileWithSuffix = (dir,fileSuffixList) => {
	return new Promise( resolve => {
		fs.readdir(dir, (err, files) => {
		  if (err) {
		    resolve(['读取失败：${dir}'])
		  } else {
		  	const file = files.find(f => fileSuffixList.indexOf( path.extname(f) ) >= 0)
		  	file ? resolve([null,path.join(dir,file)]) : resolve(['file not exist!'])
		  }
		});

	})
}


exports.mkdir = (dirPath)=>{
	return new Promise( resolve => {
		fs.mkdir(dirPath, { recursive: true }, (err) => {
		  if (err) {
		  	resolve([`创建文件夹错误:${dirPath}`])
		  }else{
		  	resolve([null,dirPath])
		  }
		});
	})
}

exports.moveFile = (originFile,targetFile) => {
	return new Promise( resolve => {
		fs.rename(originFile,targetFile, function (err) {
		    if (err) {
		        resolve([`移动文件错误:源${originFile} 目标:${targetFile}`])
		    } else {
		    	resolve([])
		    }
		});
	})
}